<template>
  <view class="app">
    <view class="title">🎓 学生信息管理系统</view>

    <!-- 学生信息表单组件 -->
    <StudentForm
      :newStudent="newStudent"
      :editIndex="editIndex"
      @add="addStudent"
      @update="updateStudent"
    />

    <!-- 搜索输入框 -->
    <input
      class="search-bar"
      v-model="keyword"
      placeholder="🔍 搜索学生姓名..."
    />

    <!-- AI 分析按钮 -->
    <button class="ai-button" @click="analyzeWithAI">✨ AI 智能分析</button>

    <!-- 学生信息列表组件 -->
    <StudentList
      :students="filteredStudents"
      @delete="deleteStudent"
      @edit="editStudent"
    />
  </view>
</template>

<script>
import StudentForm from "/components/StudentForm.vue";
import StudentList from "/components/StudentList.vue";
import { request } from "@/utils/request.js"; // 自定义封装的请求

export default {
  components: { StudentForm, StudentList },
  data() {
    return {
      students: [],
      newStudent: {
        sno: "",
        name: "",
        age: "",
        gender: "男",
        major: "通信工程",
      },
      editIndex: null,
      keyword: "",
    };
  },
  computed: {
    filteredStudents() {
      return this.students.filter((s) => s.name.includes(this.keyword));
    },
  },
  onLoad() {
    this.loadStudents();
  },
  methods: {
    async loadStudents() {
      try {
        const res = await request("/students");
        this.students = res;
      } catch (err) {
        console.error("获取学生失败", err);
      }
    },
    async addStudent(student) {
      try {
        await request("/students", "POST", student);
        uni.showToast({ title: "添加成功" });
        this.resetForm();
        this.loadStudents();
      } catch (err) {
        console.error("添加失败", err);
      }
    },
    async deleteStudent(index) {
      const id = this.filteredStudents[index].id;
      try {
        await request(`/students/${id}`, "DELETE");
        uni.showToast({ title: "删除成功" });
        this.loadStudents();
      } catch (err) {
        console.error("删除失败", err);
      }
    },
    editStudent(index) {
      this.newStudent = { ...this.filteredStudents[index] };
      this.editIndex = index;
    },
    async updateStudent(student) {
      try {
        await request(`/students/${student.id}`, "PUT", student);
        uni.showToast({ title: "更新成功" });
        this.resetForm();
        this.loadStudents();
      } catch (err) {
        console.error("更新失败", err);
      }
    },
    resetForm() {
      this.newStudent = {
        sno: "",
        name: "",
        age: "",
        gender: "男",
        major: "通信工程",
      };
      this.editIndex = null;
    },

    // 🌟 新增：AI 分析方法
    async analyzeWithAI() {
      try {
        // 获取学生数据
        const students = await request("/students/export");
    
        // 向 Dify 工作流发起请求
        uni.request({
          url: "http://localhost:8080/v1/workflows/run", // 换成真实接口
          method: "POST",
          header: {
            "Content-Type": "application/json",
            "Authorization": "Bearer app-kxxeqUrZMlqobeLzKTou2OZc" // 如果你的 Dify 开启了鉴权
          },
          data: {
            inputs: {
              input: JSON.stringify(students)
            },
			user: "test-user"  // 👈 必须添加一个 user 字段
          },
          success: (resp) => {
            console.log("🧠 AI响应原始数据：", resp.data); // ✅ 打印查看结构
    
            // 支持多种响应格式，自动识别最合适字段
           const result =
               resp.data.outputs?.result ||  // ✅ 正确位置
               resp.data.result ||
               resp.data.message ||
               resp.data.data ||
               resp.data.choices?.[0]?.message?.content ||
               "AI未返回有效分析内容";

    
            uni.showModal({
              title: "AI 分析报告",
              content: result,
              showCancel: false
            });
          },
          fail: (err) => {
            console.error("AI分析失败", err);
            uni.showToast({ title: "AI 请求失败", icon: "none" });
          }
        });
      } catch (err) {
        console.error("获取学生数据失败", err);
        uni.showToast({ title: "学生数据异常", icon: "none" });
      }
    },
	},
	};

</script>

<style scoped>
.app {
  padding: 30rpx;
}
.title {
  font-size: 40rpx;
  text-align: center;
  color: #2c3e50;
  font-weight: bold;
  margin-bottom: 30rpx;
}
.search-bar {
  width: 100%;
  padding: 20rpx;
  font-size: 28rpx;
  border: 1rpx solid #ccc;
  border-radius: 12rpx;
  margin-bottom: 30rpx;
  background-color: #ffffff;
}
/* 🌟 新增：AI分析按钮 */
.ai-button {
  width: 100%;
  background-color: #409eff;
  color: white;
  padding: 20rpx;
  font-size: 28rpx;
  border: none;
  border-radius: 12rpx;
  margin-bottom: 30rpx;
}
</style>

